# helper functions for twitter oauth
# most of this is taken from the examples of simplegeo-oauth

import urlparse
import oauth2 as oauth
import libpub
import base64

#
# authenticate with twitter via browser and pin
#

class browserAuth:
    twitpic=None
    oauth_token=None
    oauth_token_secret=None
    consumer=None
    client=None

    request_token=None

    request_token_url = 'http://twitter.com/oauth/request_token'
    access_token_url = 'http://twitter.com/oauth/access_token'
    authorize_url = 'http://twitter.com/oauth/authorize'

    def getAuthUrl(self):
        k=authCodes()
        self.consumer = oauth.Consumer(k.obf(k.ck()), k.obf(k.cs()))
        self.client = oauth.Client(self.consumer)

        resp, content = self.client.request(self.request_token_url, "GET")
        if resp['status'] != '200':
            raise Exception("Invalid response %s." % resp['status'])

        self.request_token = dict(urlparse.parse_qsl(content))

        twitter_url="%s?oauth_token=%s" % (self.authorize_url, self.request_token['oauth_token'])

        return twitter_url
        # the rest has to be done after the user enters the PIN

    def validate(self,pin):
        token = oauth.Token(self.request_token['oauth_token'],
                            self.request_token['oauth_token_secret'])
        token.set_verifier(pin)
        client = oauth.Client(self.consumer, token)

        resp, content = client.request(self.access_token_url, "POST")

        if resp['status'] != '200':
            raise Exception("Invalid response %s." % resp['status'])

        access_token = dict(urlparse.parse_qsl(content))

        return (access_token['oauth_token'], access_token['oauth_token_secret'])

class authCodes:
# keep from showing up in websearch
    def ck(self):
        return 'ZWtTbVp1M1dPenRHNXBUYlM2TW9FQQ=='

    def cs(self):
        return 'RXc0anhZMWhDZ0VGc0ZscktvaXdOT05qbHFLOEtpcWdEWnVYTjR4SnFMMA=='

    def tp(self):
        return 'ZmZhNTI5N2M1ZDQ3MDY3MzI4MTQ1NzE3NmQzN2EyYWI='

    def yf(self):
        return 'NjhCRlFSWFkzYzRjYTRkNmFiNTAzMmIzNTdlNDI1MzZkNGM3MDI5YQ=='

    def obf(self,msg):
        return base64.b64decode(msg)

